//
//  StockTimeVolumeView.m
//  K线图自治
//
//  Created by LK-IOS on 2017/12/18.
//  Copyright © 2017年 LK-IOS. All rights reserved.
//

#import "StockTimeVolumeView.h"
#import "UIView+StockViewExtension.h"
#import "UIColor+StockColorEntension.h"
#import "StockConst.h"
#import "StockTimeVolumePositionModel.h"



@interface StockTimeVolumeView()

/**
 当前绘制在屏幕上的数据源数组
 */
@property (nonatomic, strong) NSArray <__kindof StockTimeLineModel*>*timeLineModels;

/**
 边框图层
 */
@property (nonatomic,strong) CAShapeLayer *boxLayer;

/**
 绘制在当前屏幕上的数据源数组
 */
@property (nonatomic , strong) NSMutableArray *drawLineModelArray;

/**
 绘制在当前屏幕上的数据位置的数组
 */
@property (nonatomic , strong) NSMutableArray *drawLinePositionModelArray;


/**
 当前选择的模型索引
 */
@property (nonatomic,assign) NSInteger curentModelIndex;

@end

@implementation StockTimeVolumeView

-(NSMutableArray *)drawLineModelArray
{
    if (_drawLineModelArray == nil) {
        _drawLineModelArray = [NSMutableArray array];
    }
    return _drawLineModelArray;
}
-(NSMutableArray *)drawLinePositionModelArray
{
    if (_drawLinePositionModelArray == nil) {
        _drawLinePositionModelArray = [NSMutableArray array];
    }
    return _drawLinePositionModelArray;
}

-(instancetype)initWithTimeLineModels:(NSArray<__kindof StockTimeLineModel *> *)timeLineModels
{
    self = [super init];
    if (self) {
        _timeLineModels = timeLineModels;
        
        self.backgroundColor = [UIColor whiteColor];
        
        
    }
    return self;
}
-(void)reDrawWithTimeLineModels:(NSArray<__kindof StockTimeLineModel *> *)timeLineModels
{
    _timeLineModels = timeLineModels;
    
    [self setNeedsDisplay];
}

- (void)drawRect:(CGRect)rect
{
    [super drawRect:rect];
    [self draw];
}
-(void)draw
{
    [self addBoxLayer];//添加边框图层
    [self addDotLine];//添加成交量视图上面的虚线
    
    if (self.timeLineModels.count <= 0)return;
    
    [self initConfig];//初始化属性
    [self resloveDataArray];//处理数据数组
    [self startDrawVolumeChart];//开始绘制
    [self addCurrentVolumeLabel];//添加当前成交量label
    [self addMaxMinVolumeLabel];//添加最高和最低成交量

}

/**
 添加边框图层
 */
-(void)addBoxLayer
{
    //创建边框图层
    self.boxLayer = [CAShapeLayer layer];
    self.boxLayer.frame = CGRectMake(0, 0, CGRectGetWidth(self.frame), CGRectGetHeight(self.frame));
    self.boxLayer.contentsScale = [UIScreen mainScreen].scale;
    self.boxLayer.strokeColor = [UIColor clearColor].CGColor;
    self.boxLayer.fillColor = [UIColor clearColor].CGColor;
    [self.layer addSublayer:self.boxLayer];
    
    //边框图层
    //左
    CAShapeLayer *leftLayer = [self getAxispLayer];
    leftLayer.lineWidth = TimeLineBoxLineWidth * 0.5;
    UIBezierPath *leftPath = [UIBezierPath bezierPath];
    [leftPath moveToPoint:CGPointMake(TimeLineLeftMargin,0)];
    [leftPath addLineToPoint:CGPointMake(TimeLineLeftMargin, self.height - self.bottomMargin)];
    leftLayer.path = leftPath.CGPath;
    [self.boxLayer addSublayer:leftLayer];
    //右
    CAShapeLayer *rightLayer = [self getAxispLayer];
    rightLayer.lineWidth = TimeLineBoxLineWidth * 0.5;
    UIBezierPath *rightPath = [UIBezierPath bezierPath];
    [rightPath moveToPoint:CGPointMake(self.width - TimeLineRightMargin,0)];
    [rightPath addLineToPoint:CGPointMake(self.width - TimeLineRightMargin, self.height - self.bottomMargin)];
    rightLayer.path = rightPath.CGPath;
    [self.boxLayer addSublayer:rightLayer];
    //上
    CAShapeLayer *topLayer = [self getAxispLayer];
    topLayer.lineWidth = TimeLineBoxLineWidth * 0.5;
    UIBezierPath *topPath = [UIBezierPath bezierPath];
    [topPath moveToPoint:CGPointMake(TimeLineLeftMargin,0)];
    [topPath addLineToPoint:CGPointMake(self.width - TimeLineRightMargin, 0)];
    topLayer.path = topPath.CGPath;
    [self.boxLayer addSublayer:topLayer];
    //下
    CAShapeLayer *bottomLayer = [self getAxispLayer];
    bottomLayer.lineWidth = TimeLineBoxLineWidth * 0.5;
    UIBezierPath *bottomPath = [UIBezierPath bezierPath];
    [bottomPath moveToPoint:CGPointMake(TimeLineLeftMargin,self.height - self.bottomMargin)];
    [bottomPath addLineToPoint:CGPointMake(self.width - TimeLineRightMargin,self.height - self.bottomMargin)];
    bottomLayer.path = bottomPath.CGPath;
    [self.boxLayer addSublayer:bottomLayer];
}

/**
 添加成交量视图上面的虚线
 */
-(void)addDotLine
{
    //横线
    CGFloat y = self.height * 0.5;
    CAShapeLayer *layer = [CAShapeLayer layer];
    layer.lineWidth = TimeLineLineWidth;
    layer.strokeColor = [UIColor Stock_TimeBackLineColor].CGColor;
    [layer setLineDashPattern:[NSArray arrayWithObjects:[NSNumber numberWithInt:2],[NSNumber numberWithInt:1],nil]];
    UIBezierPath *path = [UIBezierPath bezierPath];
    [path moveToPoint:CGPointMake(TimeLineLeftMargin,y)];
    [path addLineToPoint:CGPointMake(self.width - TimeLineRightMargin,y)];
    layer.path = path.CGPath;
    [self.layer addSublayer:layer];
    
    //纵线
    for (NSInteger i = 1;i < 3;i++)
    {
        CGFloat x = self.width/3*(i);
        CAShapeLayer *layer = [CAShapeLayer layer];
        layer.lineWidth = TimeLineLineWidth;
        layer.strokeColor = [UIColor Stock_TimeBackLineColor].CGColor;
        [layer setLineDashPattern:[NSArray arrayWithObjects:[NSNumber numberWithInt:2],[NSNumber numberWithInt:1],nil]];
        UIBezierPath *path = [UIBezierPath bezierPath];
        [path moveToPoint:CGPointMake(x,0)];
        [path addLineToPoint:CGPointMake(x,self.height)];
        layer.path = path.CGPath;
        [self.layer addSublayer:layer];
    }
}

/**
 初始化属性
 */
-(void)initConfig
{
    //线宽
    self.lineSpace = TimeLineVolumeLineSpace;
    self.lineWidth  = (self.width - TimeLineLeftMargin - TimeLineRightMargin -(TimeLineTimesCount -1)*self.lineSpace)/TimeLineTimesCount;
}
/**
 处理数据数组
 */
-(void)resloveDataArray
{
    [self.drawLineModelArray removeAllObjects];
    
    
    [self.drawLineModelArray addObjectsFromArray:self.timeLineModels];
    
    [self convertToPositionModelsWithXPosition:TimeLineLeftMargin drawLineModels:self.drawLineModelArray];
}

/**
 转换坐标
 @param startX 分时图开始位点默认为0，
 @param drawLineModels 当前界面上的数据数组
 */
- (void)convertToPositionModelsWithXPosition:(CGFloat)startX drawLineModels:(NSMutableArray<__kindof StockTimeLineModel*>*)drawLineModels
{
    //无数据直接返回
    if (!drawLineModels) return;
    
    [self.drawLinePositionModelArray removeAllObjects];
    //获取数据源的最大值及最小值
    CGFloat minValue =  [[[drawLineModels valueForKeyPath:@"CurrentVolume"] valueForKeyPath:@"@min.floatValue"] floatValue];
    CGFloat maxValue =  [[[drawLineModels valueForKeyPath:@"CurrentVolume"] valueForKeyPath:@"@max.floatValue"] floatValue];
    //成交量视图Y轴方向上的最大值及最小值
    CGFloat minY = TimeLineVolumeLineSpace;
    CGFloat maxY = self.height - TimeLineVolumeLineSpace;
    //缩放比例
    CGFloat unitValue = (maxValue - minValue)/(maxY - minY);
    
    [drawLineModels enumerateObjectsUsingBlock:^(id<PZStockTimeLineProtocol>  _Nonnull model, NSUInteger idx, BOOL * _Nonnull stop) {
        
        //定位每个数据的X点
        CGFloat xPosition = startX + idx * (self.lineWidth + self.lineSpace);
        //定位每个数据的Y点
        CGFloat yPosition = ABS(maxY - ([[NSString stringWithFormat:@"%@" , model.currentVolume] floatValue] - minValue)/unitValue);
        //整个方块区域的开始点
        CGPoint startPoint = CGPointMake(xPosition, ABS(yPosition - maxY) > 1 ? yPosition : maxY );
        //整个方块的结束点
        CGPoint endPoint = CGPointMake(xPosition, maxY);
        
        //根据每条数据获取的开始点结束点，以及时间，创建每一个成交量模型
        StockTimeVolumePositionModel *positionModel = [StockTimeVolumePositionModel modelWithStartPoint:startPoint endPoint:endPoint dayDesc:model.currentTime];
        [self.drawLinePositionModelArray addObject:positionModel];
        
    }];
}

/**
 开始绘制成交量视图
 */
-(void)startDrawVolumeChart
{
    /*
     分时的成交量图，红色代表在昨日收盘价以上成交的，绿色代表在昨日收盘价一下成交的
     */
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    if (!self.drawLinePositionModelArray)return;
    
    [self.drawLinePositionModelArray enumerateObjectsUsingBlock:^(StockTimeVolumePositionModel  *_Nonnull pModel, NSUInteger idx, BOOL * _Nonnull stop) {
        
        //计算涨跌幅度,目前暂时以涨跌幅度为买入卖出的标准
        CGFloat changeRate =[[self.timeLineModels[idx] priceChange] floatValue];
        //绘制成交量线
        if (changeRate >= 0) {
            
            CGContextSetStrokeColorWithColor(ctx, [UIColor Stock_PriceUpColor].CGColor);
            CGContextSetLineWidth(ctx, self.lineWidth);
            const CGPoint solidPoints[] = {pModel.StartPoint, pModel.EndPoint};
            CGContextStrokeLineSegments(ctx, solidPoints, 2);
        }else{
            CGContextSetStrokeColorWithColor(ctx, [UIColor Stock_PriceDownColor].CGColor);
            CGContextSetLineWidth(ctx, self.lineWidth);
            const CGPoint solidPoints[] = {pModel.StartPoint, pModel.EndPoint};
            CGContextStrokeLineSegments(ctx, solidPoints, 2);
        }
    }];
}

/**
 添加当前成交量label
 */
-(void)addCurrentVolumeLabel
{
    StockTimeLineModel *model = self.timeLineModels.lastObject;
    
    CGFloat volume = [model.currentVolume floatValue];
    if (volume > 0) {
        //尝试转为万手
        CGFloat wVolume = volume/10000.f;
        NSString *text, *descText;
        if (wVolume > 1) {
            //尝试转为亿手
            CGFloat yVolume = wVolume/10000.f;
            if (yVolume > 1) {
                text = [NSString stringWithFormat:@"%.2f",yVolume];
                descText = @"亿手";
            } else {
                text = [NSString stringWithFormat:@"%.2f",wVolume];
                descText = @"万手";
            }
        } else {
            text = [NSString stringWithFormat:@"%.0f",volume];
            descText = @"手";
        }
        
        NSString *labelText = [NSString stringWithFormat:@"当前量:%@%@" , text , descText];
        NSDictionary *attribute = @{NSFontAttributeName:[UIFont systemFontOfSize:font12ScreenWRate * LKScreenW],NSForegroundColorAttributeName:[UIColor Stock_TextColor] , NSBackgroundColorAttributeName :[UIColor clearColor]};
        CGRect textRect = [self rectOfNSString:labelText attribute:attribute];
        
        [labelText drawInRect:CGRectMake(TimeLineLeftMargin, 0, textRect.size.width, textRect.size.height) withAttributes:attribute];
    }else{//成交量为0不现实成交量
       
    }

}

/**
 添加最低和最高成交量label
 */
-(void)addMaxMinVolumeLabel
{
    CGFloat maxValue =  [[[self.timeLineModels valueForKeyPath:@"CurrentVolume"] valueForKeyPath:@"@max.floatValue"] floatValue];
    if (maxValue <= 0)return;
    CGFloat middleValue = maxValue * 0.5;
    
    NSString *maxValueString = [NSString stringWithFormat:@"%.2f" , maxValue];
    NSString *middleValueString = [NSString stringWithFormat:@"%.2f" , middleValue];
    NSString *minValueString = @"0.00";
    
    NSDictionary *attribute = @{NSFontAttributeName:[UIFont systemFontOfSize:font12ScreenWRate * LKScreenW],NSForegroundColorAttributeName:[UIColor lightGrayColor] , NSBackgroundColorAttributeName :[UIColor clearColor]};
    
    CGRect maxRect = [self rectOfNSString:maxValueString attribute:attribute];
    CGRect middleRect = [self rectOfNSString:middleValueString attribute:attribute];
    CGRect minRect = [self rectOfNSString:minValueString attribute:attribute];
    
    [maxValueString drawInRect:CGRectMake(self.width - TimeLineRightMargin - maxRect.size.width, 0, maxRect.size.width, maxRect.size.height) withAttributes:attribute];
    
    [middleValueString drawInRect:CGRectMake(self.width - TimeLineRightMargin - middleRect.size.width, self.height * 0.5 - middleRect.size.height * 0.5, middleRect.size.width, middleRect.size.height) withAttributes:attribute];

    [minValueString drawInRect:CGRectMake(self.width - TimeLineRightMargin - minRect.size.width, self.height - minRect.size.height , minRect.size.width, minRect.size.height) withAttributes:attribute];

}

/**
 获取长按时的坐标点
 */
- (CGPoint)getLongPressModelPostionWithXPostion:(CGFloat)xPostion
{
    //整体遍历一下，看当前的手势点在不在当前数据范围内
    for (NSInteger i = 0; i<self.drawLinePositionModelArray.count; i++) {
        StockTimeVolumePositionModel *model = self.drawLinePositionModelArray[i];
        CGFloat minX = fabs(model.StartPoint.x - TimeLineLineWidth);
        CGFloat maxX = model.EndPoint.x + TimeLineLineWidth;
        
        if (xPostion - TimeLineLeftMargin>= minX && xPostion - TimeLineRightMargin  < maxX)
        {
            _curentModelIndex = i;
            return CGPointMake(model.StartPoint.x , model.StartPoint.y);
        }
    }
    //是不是最后一条数据
    StockTimeVolumePositionModel *lastPoint = _drawLinePositionModelArray.lastObject;
    if (xPostion >= lastPoint.EndPoint.x)
    {
        _curentModelIndex = _drawLinePositionModelArray.count - 1;
        return CGPointMake(lastPoint.StartPoint.x, lastPoint.StartPoint.y);
    }
    //是不是第一条数据
    StockTimeVolumePositionModel *firstPoint = _drawLinePositionModelArray.firstObject;
    if (fabs(xPostion - TimeLineLeftMargin)  <= firstPoint.StartPoint.x)
    {
        _curentModelIndex = 0;
        return CGPointMake(firstPoint.StartPoint.x, firstPoint.StartPoint.y);
    }
    return CGPointZero;
}

- (CGPoint)getLastModelPostion
{
    if (_drawLinePositionModelArray.count>0)
    {
        StockTimeVolumePositionModel *lastPoint = _drawLinePositionModelArray.lastObject;
        return CGPointMake(lastPoint.StartPoint.x, lastPoint.StartPoint.y);
    }
    return CGPointZero;
}

-(StockTimeLineModel *)getLongPressModel
{
    StockTimeLineModel *model = _timeLineModels[_curentModelIndex];
    
    return model;
}


/**
 创建边框图层
 */
- (CAShapeLayer*)getAxispLayer
{
    CAShapeLayer *layer = [CAShapeLayer layer];
    layer.strokeColor = [UIColor Stock_BoxColor].CGColor;
    layer.fillColor = [[UIColor clearColor] CGColor];
    layer.contentsScale = [UIScreen mainScreen].scale;
    return layer;
}


- (CGRect)rectOfNSString:(NSString *)string attribute:(NSDictionary *)attribute
{
    CGRect rect = [string boundingRectWithSize:CGSizeMake(MAXFLOAT, 0)
                                       options:NSStringDrawingTruncatesLastVisibleLine |NSStringDrawingUsesLineFragmentOrigin |
                   NSStringDrawingUsesFontLeading
                                    attributes:attribute
                                       context:nil];
    return rect;
}

@end
